package controllers.admin;

import java.util.ArrayList;
import java.util.List;

import models.Administrator;
import models.Article;
import models.Attachment;
import models.Brand;
import models.Message;
import models.QueryBean;
import models.User;
import models.BaseEntity.Status;
import models.UserGroup;
import models.UserGroup.UserGroupType;
import controllers.GlobalVariables;
import controllers.Secure;
import controllers.ValidationUtil;
import play.data.validation.Valid;
import play.mvc.Controller;
import play.mvc.With;
import service.UserService;

@With(Secure.class)
public class Users extends Controller {
	/**
	 * 进入User管理页面。
	 */
	public static void index() {
		QueryBean queryBean = new QueryBean();
		List<UserGroup> groups = UserGroup.find("byType", UserGroupType.INHERENCE).fetch();
		render(queryBean, groups);
	}
	
	/**
	 * 查询
	 */
	public static void indexTable(QueryBean queryBean, Long group) {
		if(queryBean == null) {
			queryBean = new QueryBean();
			queryBean.isDesc = true;
		}
		StringBuilder hql = new StringBuilder("id != null ");
		List<Object> objs = new ArrayList<Object>();
		
		if(!ValidationUtil.isEmpty(queryBean.keyword)) {
    		if(ValidationUtil.isLong(queryBean.keyword)) {
    			hql.append("and (id=? or ");
        		objs.add(Long.valueOf(queryBean.keyword));
    		} else {
    			hql.append("and (");
    		}
    		hql.append("username like ? or realname like ?) ");
    		objs.add("%"+queryBean.keyword+"%");
    		objs.add("%"+queryBean.keyword+"%");
    	}
		
		if(!ValidationUtil.isEmpty(queryBean.orderby)) {
    		hql.append(" order by " + queryBean.orderby);
    		if(queryBean.isDesc) 
    			hql.append(" desc ");
    		else
    			hql.append(" asc ");
    	} else {
    		hql.append(" order by createAt desc, lastModifiedAt desc ");
    	}
		
		//页数计算
		queryBean.totalQuantity = User.count(hql.toString(), objs.toArray());
		queryBean.pageCaculate();
		
		List<User> users = User.find(hql.toString(), objs.toArray()).fetch(
				(int)queryBean.currentPage, queryBean.quantityEachPage);
		UserService.setGroup(users);
		render(users, queryBean);
	}
	
	public static void updateStatus(long id, Status status) throws Exception {
		User user = User.findById(id);
		if(user == null) {
			throw new Exception("此管理员已被删除");
		} else {
			String username = session.get(GlobalVariables.SECURE_ADMINNAME);
			Administrator longinadmin = Administrator.find("byUsername", username).first();
			user.status = status;
			user.resetModifier(longinadmin);
			user.save();
		}
	}
	
	public static void updateAuthentication(long id, boolean authentication) throws Exception {
		User user = User.findById(id);
		if(user == null){
			throw new Exception("此管理员已被删除");
		} else {
			String username = session.get(GlobalVariables.SECURE_ADMINNAME);
			Administrator longinadmin = Administrator.find("byUsername", username).first();
			user.authentication = authentication;
			user.resetModifier(longinadmin);
			user.save();
		}
	}
	
	/**
	 * 修改用户页面。
	 */
	public static void edit(Long id) {
		User user = User.findById(id);
		render(user);
	}
	
	/**
	 * 更新保存用户资料
	 */
	public static void update(@Valid User user) {
		if(validation.hasErrors()) {
			params.flash();
			validation.keep();
			render("admin/users/edit.html", user);
		}
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		
		User oriUser = User.findById(user.id);
		Attachment oriIdPhoto = oriUser.idphoto;
		if(oriIdPhoto == null || oriIdPhoto.id != user.idphoto.id) {
			if(oriIdPhoto != null) {
				oriIdPhoto.used = false;
				oriIdPhoto.resetModifier(admin);
				oriIdPhoto.save();
			}
			oriUser.idphoto = Attachment.findById(user.idphoto.id);
			oriUser.idphoto.used = true;
			oriUser.idphoto.resetModifier(admin);
			oriUser.idphoto.save();
		}
		oriUser.realname = user.realname;
		oriUser.password = user.password;
		oriUser.answer = user.answer;
		oriUser.question = user.question;
		oriUser.sex = user.sex;
		oriUser.birthday = user.birthday;
		oriUser.city = user.city;
		oriUser.province = user.province;
		oriUser.deliveryAddress = user.deliveryAddress;
		oriUser.zipcode = user.zipcode;
		oriUser.phoneNo = user.phoneNo;
		oriUser.qqNo = user.qqNo;
		oriUser.msnNo = user.msnNo;
		oriUser.email = user.email;
		oriUser.resetModifier(admin);
		oriUser.save();
		index();
	}
	
	/**
	 * 新建用户。
	 */
	public static void newUser() {
		User user = new User();
		render(user);
	}
	
	/**
	 * 保存新建用户。
	 */
	public static void saveNew(@Valid User user) {
		List<User> existUser = User.find("byUsername", user.username).fetch();
		List<Administrator> existAdmin = Administrator.find("byUsername", user.username).fetch();
		if(!ValidationUtil.isEmpty(existUser) || !ValidationUtil.isEmpty(existAdmin)) 
			validation.addError("user.username", "用户名已经存在");
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator admin = Administrator.find("byUsername", username).first();
		
		if(validation.hasErrors()) {
			params.flash();
			validation.keep();
			render("admin/users/newUser.html", user);
		}
		
		Attachment idPhoto = Attachment.findById(user.idphoto.id);
		if(idPhoto != null) {
			idPhoto.used = true;
			idPhoto.resetModifier(admin);
			idPhoto.save();
		}
		user.authentication = false;
		user.setCreator(admin);
		user.resetModifier(admin);
		user.save();
		
		UserGroup group = UserGroup.find("byIsDefault", true).first();
		if(user.groups == null) user.groups = new ArrayList<UserGroup>();
		user.groups.add(group);
		if(group.users == null) group.users = new ArrayList<User>();
		group.users.add(user);
		user.save();
		index();
	}
	
	/**
	 * 修改用户组。
	 * @param id
	 */
	public static void editGroup(Long id) {
		User user = User.findById(id);
		UserService.setGroup(user);
		List<UserGroup> groups = UserGroup.find("byType", UserGroup.UserGroupType.INHERENCE).fetch();
		render(user, groups);
	}
	
	/**
	 * 更新用户所管理的用户组。
	 * @param id
	 * @param groupId
	 */
	public static void updateUserGroup(Long id, Long groupId) {
		User user = User.findById(id);
		UserService.setGroup(user);
		user.groups.remove(user.group);
		user.save();
		UserGroup group = UserGroup.findById(groupId);
		user.groups.add(group);
		user.save();
		index();
	}
}